package com.ruoyi.system.service.impl;
import com.google.common.collect.Maps;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.bean.StreamBean;
import com.ruoyi.common.utils.echarts.EchartsUtil;
import com.ruoyi.common.utils.html.HTMLToPDFUtils;
import com.ruoyi.common.utils.pdf.PdfReport;
import com.ruoyi.common.utils.pdf.PdfUtil;
import com.ruoyi.common.utils.sms.SmsUtils;
import com.ruoyi.system.config.SystemConfig;
import com.ruoyi.system.domain.Surver;
import com.ruoyi.system.domain.SurverOption;
import com.ruoyi.system.domain.SurverProblem;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.domain.SysDeviceData;
import com.ruoyi.system.domain.SysDeviceOmen;
import com.ruoyi.system.domain.SysMessage;
import com.ruoyi.system.domain.SysRadarData;
import com.ruoyi.system.domain.SysReport;
import com.ruoyi.system.domain.SysRoom;
import com.ruoyi.system.domain.SurverAnswer;
import com.ruoyi.system.domain.SysSong;
import com.ruoyi.system.mapper.SurverAnswerMapper;
import com.ruoyi.system.mapper.SurverMapper;
import com.ruoyi.system.mapper.SurverOptionMapper;
import com.ruoyi.system.mapper.SurverProblemMapper;
import com.ruoyi.system.mapper.SysDeviceDataMapper;
import com.ruoyi.system.mapper.SysDeviceMapper;
import com.ruoyi.system.mapper.SysDeviceOmenMapper;
import com.ruoyi.system.mapper.SysMessageMapper;
import com.ruoyi.system.mapper.SysRadarDataMapper;
import com.ruoyi.system.mapper.SysReportMapper;
import com.ruoyi.system.mapper.SysRoomMapper;
import com.ruoyi.system.mapper.SysSongMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ICommonService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (SysDeviceData)表服务实现类
 *
 * @author makejava
 * @since 2022-03-16 10:44:35
 */
@Slf4j
@Service
@Transactional(rollbackFor=Exception.class)
public class CommonServiceImpl implements ICommonService {

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private SysDeviceMapper deviceMapper;

    @Resource
    private SysDeviceDataMapper deviceDataMapper;

    @Resource
    private SysMessageMapper messageMapper;

    @Autowired
    private SysRadarDataMapper radarDataMapper;

    @Autowired
    private SysRoomMapper roomMapper;

    @Autowired
    private SysReportMapper reportMapper;

    @Autowired
    private SurverMapper surverMapper;

    @Autowired
    private SurverProblemMapper problemMapper;

    @Autowired
    private SurverOptionMapper optionMapper;

    @Autowired
    private SurverAnswerMapper answerMapper;

    @Autowired
    private SysDeviceOmenMapper deviceOmenMapper;

    @Autowired
    private SysSongMapper songMapper;

    //spring提供的推送方式
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Override
    public String queryReportUrl(Long userId,Long deviceDataId,String conclusion,String programme) throws Exception {
//        Desktop.getDesktop().browse(new URL("http://localhost/serial/imgtest").toURI());
//        Robot robot = new Robot();
//        robot.delay(10000);
//        Dimension d = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
//        int width = (int) d.getWidth();
//        int height = (int) d.getHeight();
//        //最大化浏览器
//        robot.keyRelease(KeyEvent.VK_F11);
//        robot.delay(2000);
//        Image image = robot.createScreenCapture(new Rectangle(0, 0, width,
//                height));
//        BufferedImage bi = new BufferedImage(width, height,
//                BufferedImage.TYPE_INT_RGB);
//        Graphics g = bi.createGraphics();
//        g.drawImage(image, 0, 0, width, height, null);
//        //保存图片
//        ImageIO.write(bi, "jpg", new File(RuoYiConfig.getUploadPath() + "html.jpg"));
        HTMLToPDFUtils.htmlToImg("https://sunfu.xdkdate.com/common/pdfimg?deviceDataId="+deviceDataId,"/home/sunfu_back/uploadPath/" + deviceDataId + ".jpg","--width 348 --height 355");
//        HTMLToPDFUtils.htmlToImg("https://www.bythealthy.com/sunfu/common/pdfimg?deviceDataId="+deviceDataId,"C:/msznyl/uploadPath/" + deviceDataId + ".jpg","--width 348 --height 355");
        PdfReport.createDocument(userMapper.selectUserById(userId),conclusion,programme,"/home/sunfu_back/uploadPath/" + deviceDataId + ".jpg","/home/sunfu_back/uploadPath/" + deviceDataId + ".pdf","人体运动功能检测评估报告","Author@xdk","Subject@xdk","Keywords@xdk","Creator@xdk","XDK");
//        PdfReport.createDocument(userMapper.selectUserById(userId),conclusion,programme,"C:/msznyl/uploadPath/" + deviceDataId + ".jpg","C:/msznyl/uploadPath/" + deviceDataId + ".pdf","人体运动功能检测评估报告","Author@xdk","Subject@xdk","Keywords@xdk","Creator@xdk","XDK");
        return "https://sunfu.xdkdate.com/profile/" + deviceDataId + ".pdf";
//        return "https://www.bythealthy.com/sunfu/profile/" + deviceDataId + ".pdf";
    }

    @Override
    public void sendIm(long userId,int position,int pointNum,String message) {
        SysUser user = userMapper.selectUserById(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("name", user.getUserName());
        map.put("position", position);
        map.put("pointNum", pointNum);
        Map<String,Object> wave = new HashMap<>();
        SysMessage sysMessage = new SysMessage();
        sysMessage.setUserId(userId);
        sysMessage.setPosition(position);
        sysMessage.setPointNum(pointNum);
        if(pointNum == 4) {
            String[] data = message.split(",");
            for (int i = 0; i < 4; i++) {
                if (StringUtils.isNull(data[i]) || Integer.parseInt(data[i]) <= 5) {
                    map.put("data" + i, 0);
                } else {
                    map.put("data" + i, data[i]);
                }
                if (StringUtils.isNull(data[i]) || Integer.parseInt(data[i]) <= 33) {
                    wave.put("foot" + (i + 1) + "wave", 0);
                } else {
                    wave.put("foot" + (i + 1) + "wave", data[i]);
                }
            }

        }else if(pointNum == 8){
            String[] data = new String[8];
            for (int i = 0; i < 8; i++) {
                data[i] = message.substring(i*2,i*2+2);
            }
            for (int i = 0; i < 8; i++) {
                if(Integer.parseInt(data[i],2) == 0){
                    map.put("data" + i,25);
                }else if(Integer.parseInt(data[i],2) == 1){
                    map.put("data" + i,50);
                }else if(Integer.parseInt(data[i],2) == 2){
                    map.put("data" + i,75);
                }else if(Integer.parseInt(data[i],2) == 3){
                    map.put("data" + i,100);
                }
            }
        }
        sysMessage.setMessage(message);
        sysMessage.setCreateBy("admin");
        sysMessage.setCreateTime(new Date());
        messageMapper.insert(sysMessage);
        messagingTemplate.convertAndSend("/topic/broadcast", map);
        messagingTemplate.convertAndSendToUser("footwave", "/message", wave);
    }

    @Override
    public void sendLineIm(Long userId, String startTime, String endTime) throws InterruptedException {
        Thread thread = new Thread(){
            @Override
            @SneakyThrows
            public void run(){
                List<SysMessage> sysMessageList = messageMapper.queryAllGroupByTime(userId,startTime,endTime);
                for (int i = 0; i < sysMessageList.size(); i++) {
                    SysUser user = userMapper.selectUserById(sysMessageList.get(i).getUserId());
                    Map<String,Object> map = new HashMap<>();
                    map.put("userId", sysMessageList.get(i).getUserId());
                    map.put("name", user.getUserName());
                    map.put("position", sysMessageList.get(i).getPosition());
                    map.put("pointNum", sysMessageList.get(i).getPointNum());
                    if(sysMessageList.get(i).getPointNum() == 4) {
                        String[] data = sysMessageList.get(i).getMessage().split(",");
                        for (int j = 0; j < 4; j++) {
                            map.put("data" + j, data[j]);
                        }
                    }else if(sysMessageList.get(i).getPointNum() == 8){
                        String[] data = new String[8];
                        for (int j = 0; j < 8; j++) {
                            data[j] = sysMessageList.get(j).getMessage().substring(j*2,j*2+2);
                        }
                        for (int j = 0; j < 8; j++) {
                            if(Integer.parseInt(data[j],2) == 0){
                                map.put("data" + j,25);
                            }else if(Integer.parseInt(data[j],2) == 1){
                                map.put("data" + j,50);
                            }else if(Integer.parseInt(data[j],2) == 2){
                                map.put("data" + j,75);
                            }else if(Integer.parseInt(data[j],2) == 3){
                                map.put("data" + j,100);
                            }
                        }
                    }
                    messagingTemplate.convertAndSendToUser(userId.toString(),"/message", map);
                    Thread.sleep(1000);
                }
            }
        };
        thread.start();
        CacheUtils.put(Constants.SYS_THREAD_CACHE,Constants.SYS_THREAD_KEY + userId,thread);
    }

    @Override
    public void sendImTest(Long userId,String message) {
        messagingTemplate.convertAndSendToUser(userId.toString(),"/message", message);
    }

    @Override
    public void stopLineIm(Long userId) {
        Thread thread = (Thread) CacheUtils.get(Constants.SYS_THREAD_CACHE,Constants.SYS_THREAD_KEY + userId);
        thread.stop();
    }

    @Override
    public List<SysUser> queryUserByUserId(Long userId) {
        return userMapper.selectUserByReceiveId(userId);
    }

    @Override
    public List<SysDeviceData> queryDeviceDataByUserId(Long userId) {
        return deviceDataMapper.queryDataByUser(userId);
    }

    @Override
    public void sendUserId(Long userId) {
        SysUser user = userMapper.selectUserById(userId);
        messagingTemplate.convertAndSend("/topic/broadcast", user);
    }

    @Override
    public void sendUserIMTest() {
        messagingTemplate.convertAndSendToUser("test","/message", "IM测试");
    }

    @Override
    public String queryDeviceDataById(Long deviceDataId) {
        SysDeviceData sysDeviceData = deviceDataMapper.queryById(deviceDataId);
        return sysDeviceData.getDeviceDataValue();
    }

    @Override
    public List<SysDevice> queryDeviceByUserId(Long userId) {
        SysUser user = userMapper.selectUserById(userId);
        List<SysDevice> deviceList = deviceMapper.queryByDeptId(user.getDeptId());
        return deviceList;
    }

    @Async
    @Override
    public void saveRadarData(String deviceCode, String dataKey, String dataValue, Date now) {
        Integer someoneExists = (Integer) CacheUtils.get(Constants.SYS_RADAR_CACHE,Constants.SYS_RADAR_KEY + deviceCode);
        Long userId = roomMapper.queryUserIdByDeviceCode(deviceCode);
        if (StringUtils.isNotNull(userId)) {
            if(StringUtils.isNull(someoneExists) || someoneExists == 1) {
                if(dataKey.equals("someoneExists")  && dataValue.equals("0")){
                    SysRadarData radarData = radarDataMapper.querySomeoneExistsByExist(deviceCode);
                    radarData.setUpdateTime(now);
                    radarDataMapper.update(radarData);
                }

                SysRadarData radarData = new SysRadarData();
                radarData.setUserId(userId);
                radarData.setDeviceCode(deviceCode);
                radarData.setDeviceType(4);
                radarData.setDeviceDataKey(dataKey);
                radarData.setDeviceDataValue(dataValue);
                radarData.setCreateBy("admin");
                radarData.setCreateTime(now);
                if(!((dataKey.equals("heartRateValue") || dataKey.equals("breathValue")) && dataValue.equals("0"))){
                    radarDataMapper.insert(radarData);
                }

                if (dataKey.equals("heartRateValue") && dataValue.equals("0")) {
                    int heartNum = SystemConfig.heartNumMap.get(deviceCode);
                    heartNum++;
                    SystemConfig.heartNumMap.put(deviceCode,heartNum);
                    if(heartNum >= 6) {
                        CacheUtils.put(Constants.SYS_RADAR_CACHE, Constants.SYS_RADAR_KEY + deviceCode, 0);
                        SysRadarData sleepStatus = new SysRadarData();
                        sleepStatus.setUserId(userId);
                        sleepStatus.setDeviceCode(deviceCode);
                        sleepStatus.setDeviceType(4);
                        sleepStatus.setDeviceDataKey("sleepStatus");
                        sleepStatus.setDeviceDataValue("3");
                        sleepStatus.setCreateTime(now);
                        sleepStatus.setCreateBy("admin");
                        radarDataMapper.insert(sleepStatus);
                        SysRadarData motionStatus = new SysRadarData();
                        motionStatus.setUserId(userId);
                        motionStatus.setDeviceCode(deviceCode);
                        motionStatus.setDeviceType(4);
                        motionStatus.setDeviceDataKey("motionStatus");
                        motionStatus.setDeviceDataValue("0");
                        motionStatus.setCreateTime(now);
                        motionStatus.setCreateBy("admin");
                        radarDataMapper.insert(motionStatus);
                        SysRadarData someoneExistsMap = new SysRadarData();
                        someoneExistsMap.setUserId(userId);
                        someoneExistsMap.setDeviceCode(deviceCode);
                        someoneExistsMap.setDeviceType(4);
                        someoneExistsMap.setDeviceDataKey("someoneExists");
                        someoneExistsMap.setDeviceDataValue("0");
                        someoneExistsMap.setCreateTime(now);
                        someoneExistsMap.setCreateBy("admin");
                        radarDataMapper.insert(someoneExistsMap);
                        Long dataId = radarDataMapper.queryMaxSomeoneExistsId(userId, deviceCode, "1");
                        if(StringUtils.isNotNull(dataId)) {
                            SysRadarData srd = radarDataMapper.queryById(dataId);
                            int milli = (int) ((now.getTime() - srd.getCreateTime().getTime()) / (60 * 60 * 1000));
                            if (milli < 2) {
                                radarDataMapper.updateInvalid(userId, deviceCode, DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, srd.getCreateTime()), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, now));
                            }
                            Map<String, Object> map = new HashMap<>();
                            map.put("deviceCode", deviceCode);
                            map.put("key", "someoneExists");
                            map.put("value", "无人");
                            messagingTemplate.convertAndSendToUser("radars", "/message", map);
                        }
                    }
                }
                if (dataKey.equals("movementSigns")) {
                    Long dataId = radarDataMapper.queryMaxSomeoneExistsId(userId, deviceCode, "1");
                    if(StringUtils.isNotNull(dataId)){
                        SysRadarData srd = radarDataMapper.queryById(dataId);
                        int milli = (int) (((now.getTime() - srd.getCreateTime().getTime()) / (1000)) % (30 * 60));
                        if (milli == 0) {
                            Date semih = new Date(now.getTime() - (30 * 60 * 1000));
                            int count = radarDataMapper.querySemih(userId, deviceCode, DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, semih), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, now));
                            SysRadarData rd = new SysRadarData();
                            rd.setUserId(userId);
                            rd.setDeviceCode(deviceCode);
                            rd.setDeviceType(4);
                            rd.setDeviceDataKey("sleepStatus");
                            rd.setCreateTime(srd.getCreateTime());
                            rd.setCreateBy("admin");
                            if (count < 2) {
                                rd.setDeviceDataValue("0");
                                radarDataMapper.insert(rd);
                            } else if (count >= 2 && count < 4) {

                                rd.setDeviceDataValue("1");
                                radarDataMapper.insert(rd);
                            } else if (count >= 4) {
                                rd.setDeviceDataValue("2");
                                radarDataMapper.insert(rd);
                            }
                        }
                    }
                }
                if(dataKey.equals("breathWave")){
                    dataValue = dataValue.replace("[","").replace("]","");
                    String[] breaths = dataValue.split(",");
                    boolean isBreathStop = true;
                    for (String str:breaths) {
                        Integer breath = Integer.parseInt(str);
                        if(breath < 120 || breath > 136){
                            isBreathStop = false;
                        }
                    }
                    Integer breathNum = (Integer) CacheUtils.get(Constants.SYS_BREATH_CACHE,Constants.SYS_BREATH_KEY + deviceCode);
                    if(isBreathStop){
                        breathNum++;
                        CacheUtils.put(Constants.SYS_BREATH_CACHE, Constants.SYS_BREATH_KEY + deviceCode, breathNum);
                    }else{
                        CacheUtils.put(Constants.SYS_BREATH_CACHE, Constants.SYS_BREATH_KEY + deviceCode, 0);
                    }
                    if(breathNum == 50){
                        SysRadarData rd = new SysRadarData();
                        rd.setUserId(userId);
                        rd.setDeviceCode(deviceCode);
                        rd.setDeviceType(4);
                        rd.setDeviceDataKey("breathStop");
                        rd.setDeviceDataValue("1");
                        rd.setCreateTime(now);
                        rd.setCreateBy("admin");
                        radarDataMapper.insert(rd);
                    }
                }
            }else{
                if (dataKey.equals("heartRateValue") && !dataValue.equals("0")) {
                    SystemConfig.heartNumMap.put(deviceCode,0);
                    CacheUtils.put(Constants.SYS_RADAR_CACHE, Constants.SYS_RADAR_KEY + deviceCode, 1);
                    SysRadarData d = new SysRadarData();
                    d.setUserId(userId);
                    d.setDeviceCode(deviceCode);
                    d.setDeviceType(4);
                    d.setDeviceDataKey("someoneExists");
                    d.setDeviceDataValue("1");
                    d.setCreateTime(now);
                    d.setCreateBy("admin");
                    radarDataMapper.insert(d);

                    SysRadarData rd = new SysRadarData();
                    rd.setUserId(userId);
                    rd.setDeviceCode(deviceCode);
                    rd.setDeviceType(4);
                    rd.setDeviceDataKey("heartRateValue");
                    rd.setDeviceDataValue(dataValue);
                    rd.setCreateTime(now);
                    rd.setCreateBy("admin");
                    radarDataMapper.insert(rd);

                    Map<String, Object> map = new HashMap<>();
                    map.put("deviceCode", deviceCode);
                    map.put("key", "someoneExists");
                    map.put("value", "有人");
                    messagingTemplate.convertAndSendToUser("radars", "/message", map);
                }
            }
        }
    }

    @Override
    public List<SysDevice> queryDeviceByDeptId(Long deptId) {
        return deviceMapper.queryByDeptId(deptId);
    }

    @Override
    public List<SysDevice> queryDeviceByType(List<Integer> deviceTypeList) {
        return deviceMapper.queryDeviceByType(deviceTypeList);
    }

    @Override
    public Long queryUserIdByDeviceCode(String deviceCode) {
        Long userId = roomMapper.queryUserIdByDeviceCode(deviceCode);
        return userId;
    }

    @Override
    public SysReport exportPdf(Long userId, List<Map<String, Object>> subtitleList) {
        String id = String.valueOf(new IdWorker().nextId());
        try {
            PdfUtil.createDocument(userMapper.selectUserById(userId),subtitleList,"/home/sunfu_back/uploadPath/" + id + "-" + userId + "-radar.pdf","睡眠报告","Author@xdk","Subject@xdk","Keywords@xdk","Creator@xdk","");
//            PdfUtil.createDocument(userMapper.selectUserById(userId),subtitleList,"C:/msznyl/uploadPath/" + id + "-" + userId + "-radar.pdf","睡眠报告","Author@xdk","Subject@xdk","Keywords@xdk","Creator@xdk","");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        radarDataMapper.deleteByUserId(userId);
        SysReport report = new SysReport();
        report.setUserId(userId);
        report.setUrl("https://sunfu.xdkdate.com/profile/" + id + "-" + userId + "-radar.pdf");
//        report.setUrl("https://www.bythealthy.com/sunfu/profile/" + id + "-" + userId + "-radar.pdf");
        report.setCreateBy("admin");
        report.setCreateTime(new Date());
        reportMapper.insert(report);
//        HTMLToPDFUtils.htmlToImg("https://sunfu.xdkdate.com/profile/" + userId + "-radar.pdf","C:/msznyl/uploadPath/" + userId + "-radar.jpg","");
        return report;
    }

    @Override
    public Map<String, Object> queryRadarData(Long userId, String deviceCode, String startTime, String endTime) {

        List<String> scaleDataX = new ArrayList<>();
        List<String> scaleDataY = new ArrayList<>();
        List<String> heartDataX = new ArrayList<>();
        List<String> heartDataY = new ArrayList<>();
        List<String> respiratoryDataX = new ArrayList<>();
        List<String> respiratoryDataY = new ArrayList<>();
        List<String> sleepDataY = new ArrayList<>();
        sleepDataY.add("深睡");
        sleepDataY.add("浅睡");
        sleepDataY.add("清醒");
        long sleepMinX = 0;
        Integer sleepType = 3;
        List<Map<String,Object>> sleepTypeItem = new ArrayList<>();
        List<Long> sleepDuration = new ArrayList<>();
        List<Long> sleepStart = new ArrayList<>();
        List<String> sleepDataX = new ArrayList<>();
        List<Integer> sleepData = new ArrayList<>();
        long sober = 0;
        long deep = 0;
        long shallow = 0;
        List<String> sportsDataY = new ArrayList<>();
        sportsDataY.add("静止");
        sportsDataY.add("活跃");
        long sportsMinX = 0;
        Integer sportsType = 0;
        List<Map<String,Object>> sportsTypeItem = new ArrayList<>();
        List<Long> sportsDuration = new ArrayList<>();
        List<Long> sportsStart = new ArrayList<>();
        List<String> sportsDataX = new ArrayList<>();
        List<Integer> sportsData = new ArrayList<>();
        List<String> deviceDataKeyList = new ArrayList<>();
        deviceDataKeyList.add("sleepScale");
        List<SysRadarData> sleepScaleList = radarDataMapper.queryScaleDataByUserId(userId,deviceCode,deviceDataKeyList,startTime);
        for (int i = 0; i < sleepScaleList.size(); i++) {
            scaleDataX.add(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,sleepScaleList.get(i).getCreateTime()));
            scaleDataY.add(sleepScaleList.get(i).getDeviceDataValue());
        }
        deviceDataKeyList.clear();
        deviceDataKeyList.add("heartRateValue");
        List<SysRadarData> heartRateValueList = radarDataMapper.queryDataByUserId(userId,deviceCode,deviceDataKeyList,startTime,endTime);
        for (int i = 0; i < heartRateValueList.size(); i++) {
            heartDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",heartRateValueList.get(i).getCreateTime()));
            heartDataY.add(heartRateValueList.get(i).getDeviceDataValue());
        }
        deviceDataKeyList.clear();
        deviceDataKeyList.add("breathValue");
        List<SysRadarData> breathValueList = radarDataMapper.queryDataByUserId(userId,deviceCode,deviceDataKeyList,startTime,endTime);
        for (int i = 0; i < breathValueList.size(); i++) {
            respiratoryDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",breathValueList.get(i).getCreateTime()));
            respiratoryDataY.add(breathValueList.get(i).getDeviceDataValue());
        }
        deviceDataKeyList.clear();
        deviceDataKeyList.add("online");
        deviceDataKeyList.add("sleepStatus");
        List<SysRadarData> sleepStatusList = radarDataMapper.queryDataByUserId(userId,deviceCode,deviceDataKeyList,startTime,endTime);
        for (int i = 0; i < sleepStatusList.size(); i++) {
            switch (sleepStatusList.get(i).getDeviceDataKey()){
                case "sleepStatus":
                    if(sleepMinX == 0 && Integer.parseInt(sleepStatusList.get(i).getDeviceDataValue()) != 3){
                        sleepMinX = sleepStatusList.get(i).getCreateTime().getTime();
                    }
                    if(Integer.parseInt(sleepStatusList.get(i).getDeviceDataValue()) != sleepType){
                        if(sleepStart.size() != 0){
//                        if(sleepDataX.size() != 0){
                            sleepDuration.add(sleepStatusList.get(i).getCreateTime().getTime() - sleepStart.get(sleepStart.size() - 1));
                            switch (sleepType){
                                case 0:
                                    deep += (sleepStatusList.get(i).getCreateTime().getTime() - sleepStart.get(sleepStart.size() - 1));
//                                    deep += (sleepStatusList.get(i).getCreateTime().getTime() - DateUtils.parseDate(sleepDataX.get(sleepDataX.size() - 1)).getTime());
                                    Map<String,Object> deepMap = new HashMap<>();
                                    deepMap.put("name","深睡");
                                    deepMap.put("color","#3c78d8");
                                    sleepTypeItem.add(deepMap);
                                    sleepData.add(0);
                                    break;
                                case 1:
                                    shallow += (sleepStatusList.get(i).getCreateTime().getTime() - sleepStart.get(sleepStart.size() - 1));
//                                    shallow += (sleepStatusList.get(i).getCreateTime().getTime() - DateUtils.parseDate(sleepDataX.get(sleepDataX.size() - 1)).getTime());
                                    Map<String,Object> shallowMap = new HashMap<>();
                                    shallowMap.put("name","浅睡");
                                    shallowMap.put("color","#4ed984");
                                    sleepTypeItem.add(shallowMap);
                                    sleepData.add(1);
                                    break;
                                case 2:
                                    sober += (sleepStatusList.get(i).getCreateTime().getTime() - sleepStart.get(sleepStart.size() - 1));
//                                    sober += (sleepStatusList.get(i).getCreateTime().getTime() - DateUtils.parseDate(sleepDataX.get(sleepDataX.size() - 1)).getTime());
                                    Map<String,Object> soberMap = new HashMap<>();
                                    soberMap.put("name","清醒");
                                    soberMap.put("color","#ffc058");
                                    sleepTypeItem.add(soberMap);
                                    sleepData.add(2);
                                    break;
                                case 3:
                                    Map<String,Object> nullMap = new HashMap<>();
                                    nullMap.put("name","无");
                                    nullMap.put("color","#fffffb");
                                    sleepTypeItem.add(nullMap);
                                    sleepData.add(null);
                                    break;
                            }
                        }
                        sleepStart.add(sleepStatusList.get(i).getCreateTime().getTime());
                        sleepData.add(null);
                        sleepDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date(sleepStatusList.get(i).getCreateTime().getTime() - 1000)));
                        sleepDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",sleepStatusList.get(i).getCreateTime()));
                        sleepType = Integer.parseInt(sleepStatusList.get(i).getDeviceDataValue());
                    }
                    break;
                case "online":
                    switch (sleepType){
                        case 0:
                            sleepData.add(0);
                            break;
                        case 1:
                            sleepData.add(1);
                            break;
                        case 2:
                            sleepData.add(2);
                            break;
                        case 3:
                            sleepData.add(null);
                            break;
                    }
                    sleepType = 3;
                    sleepStart.add(sleepStatusList.get(i).getCreateTime().getTime());
                    sleepDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",sleepStatusList.get(i).getCreateTime()));
                    break;
            }
        }
        deviceDataKeyList.clear();
        deviceDataKeyList.add("online");
        deviceDataKeyList.add("motionStatus");
        List<SysRadarData> motionStatusList = radarDataMapper.queryDataByUserId(userId,deviceCode,deviceDataKeyList,startTime,endTime);
        for (int i = 0; i < motionStatusList.size(); i++) {
            switch (motionStatusList.get(i).getDeviceDataKey()){
                case "motionStatus":
                    if(sportsMinX == 0  && Integer.parseInt(motionStatusList.get(i).getDeviceDataValue()) != 0){
                        sportsMinX = motionStatusList.get(i).getCreateTime().getTime();
                    }
                    if(Integer.parseInt(motionStatusList.get(i).getDeviceDataValue()) != sportsType){
                        if(sportsStart.size() != 0){
//                        if(sportsDataX.size() != 0){
                            sportsDuration.add(motionStatusList.get(i).getCreateTime().getTime() - sportsStart.get(sportsStart.size() - 1));
                            switch (sportsType){
                                case 0:
                                    Map<String,Object> nullMap = new HashMap<>();
                                    nullMap.put("name","无");
                                    nullMap.put("color","#fffffb");
                                    sportsTypeItem.add(nullMap);
                                    sportsData.add(null);
                                    break;
                                case 1:
                                    Map<String,Object> staticMap = new HashMap<>();
                                    staticMap.put("name","静止");
                                    staticMap.put("color","#3c78d8");
                                    sportsTypeItem.add(staticMap);
                                    sportsData.add(0);
                                    break;
                                case 2:
                                    Map<String,Object> activeMap = new HashMap<>();
                                    activeMap.put("name","活跃");
                                    activeMap.put("color","#ffc058");
                                    sportsTypeItem.add(activeMap);
                                    sportsData.add(1);
                                    break;
                            }
                        }
                        sportsStart.add(motionStatusList.get(i).getCreateTime().getTime());
                        sportsData.add(null);
                        sportsDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",new Date(motionStatusList.get(i).getCreateTime().getTime() - 1000)));
                        sportsDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",motionStatusList.get(i).getCreateTime()));
                        sportsType = Integer.parseInt(motionStatusList.get(i).getDeviceDataValue());
                    }
                    break;
                case "online":
                    switch (sportsType){
                        case 0:
                            Map<String,Object> nullMap = new HashMap<>();
                            nullMap.put("name","无");
                            nullMap.put("color","#fffffb");
                            sportsTypeItem.add(nullMap);
                            sportsData.add(null);
                            break;
                        case 1:
                            Map<String,Object> staticMap = new HashMap<>();
                            staticMap.put("name","静止");
                            staticMap.put("color","#3c78d8");
                            sportsTypeItem.add(staticMap);
                            sportsData.add(0);
                            break;
                        case 2:
                            Map<String,Object> activeMap = new HashMap<>();
                            activeMap.put("name","活跃");
                            activeMap.put("color","#ffc058");
                            sportsTypeItem.add(activeMap);
                            sportsData.add(1);
                            break;
                    }
                    sportsStart.add(motionStatusList.get(i).getCreateTime().getTime());
                    sportsDataX.add(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",motionStatusList.get(i).getCreateTime()));
                    sportsType = 0;
                    break;
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("scaleDataX",scaleDataX);
        map.put("scaleDataY",scaleDataY);
        map.put("heartDataX",heartDataX);
        map.put("heartDataY",heartDataY);
        map.put("respiratoryDataX",respiratoryDataX);
        map.put("respiratoryDataY",respiratoryDataY);
        map.put("sleepDataY",sleepDataY);
        map.put("sleepMinX",sleepMinX);
        map.put("sleepDuration", sleepDuration);
        map.put("sleepTypeItem", sleepTypeItem);
        map.put("sleepDataX", sleepDataX);
        map.put("sleepData", sleepData);
        map.put("sportsDataY",sportsDataY);
        map.put("sportsMinX",sportsMinX);
        map.put("sportsDuration",sportsDuration);
        map.put("sportsTypeItem", sportsTypeItem);
        map.put("sportsDataX", sportsDataX);
        map.put("sportsData", sportsData);
        if(heartRateValueList.size() != 0) {
            map.put("recordStart", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",heartRateValueList.get(0).getCreateTime()));
            map.put("recordEnd", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",heartRateValueList.get(heartRateValueList.size() - 1).getCreateTime()));
            map.put("totalRecord", DateUtils.getDatePoor(heartRateValueList.get(heartRateValueList.size() - 1).getCreateTime(),heartRateValueList.get(0).getCreateTime()));
            map.put("totalSleep", DateUtils.getDuration(deep + shallow));
            if(deep == 0 && shallow == 0 && sober == 0){
                map.put("sleepScale", (new BigDecimal(0.0)));
                map.put("deepRatio", (new BigDecimal(0.0)));
                map.put("shallowRatio", (new BigDecimal(0.0)));
                map.put("soberRatio", (new BigDecimal(0.0)));
            }else{
                map.put("sleepScale", (new BigDecimal(((deep + shallow) * 100.0)/(deep + shallow + sober)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                map.put("deepRatio", (new BigDecimal((deep * 100.0)/(deep + shallow + sober)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                map.put("shallowRatio", (new BigDecimal((shallow * 100.0)/(deep + shallow + sober)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
                map.put("soberRatio", (new BigDecimal((sober * 100.0)/(deep + shallow + sober)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
            }

            map.put("deepCumulative", DateUtils.getDuration(deep));
            map.put("shallowCumulative", DateUtils.getDuration(shallow));
            map.put("soberCumulative", DateUtils.getDuration(sober));
        }
        return map;
    }

    @Override
    public Map<String, Object> addRadarUser(String openid, String phone, String name, String sex, String age, String height, String weight, String medical, String urgentName, String urgentPhone) {
        Map<String,Object> map = new HashMap<>();
        String userSex = "1";
        if(sex.equals("男")){
            userSex = "0";
        }
        SysUser user = userMapper.selectUserByOpenid(openid);
        if (StringUtils.isNull(user)) {
            user = userMapper.selectUserByPhoneNumber(phone);
            if(StringUtils.isNull(user)){
                user = new SysUser();
                user.setOpenid(openid);
                user.setLoginName(phone);
                user.setUserName(name);
                user.setUserType("01");
                user.setEmail("");
                user.setPhonenumber(phone);
                user.setAddress("");
                user.setSex(userSex);
                user.setAge(age);
                user.setHeight(height);
                user.setWeight(weight);
                user.setAvatar("");
                String salt = ShiroUtils.randomSalt();
                user.setPassword(new Md5Hash(name + "123456" + salt).toHex());
                user.setSalt(salt);
                user.setStatus("0");
                user.setDelFlag("0");
                user.setCreateBy("admin");
                user.setCreateTime(new Date());
                user.setMedical(medical);
                user.setUrgentName(urgentName);
                user.setUrgentPhone(urgentPhone);
                userMapper.insertUser(user);
            }else{
                user.setOpenid(openid);
                user.setUserName(name);
                user.setUserType("01");
                user.setSex(userSex);
                user.setAge(age);
                user.setHeight(height);
                user.setWeight(weight);
                user.setMedical(medical);
                user.setUrgentName(urgentName);
                user.setUrgentPhone(urgentPhone);
                user.setUpdateBy("admin");
                user.setUpdateTime(new Date());
                userMapper.updateUser(user);
            }
        }else{
            user.setUserName(name);
            user.setPhonenumber(phone);
            user.setUserType("01");
            user.setSex(userSex);
            user.setAge(age);
            user.setHeight(height);
            user.setWeight(weight);
            user.setMedical(medical);
            user.setUrgentName(urgentName);
            user.setUrgentPhone(urgentPhone);
            user.setUpdateBy("admin");
            user.setUpdateTime(new Date());
            userMapper.updateUser(user);
        }
        try {
            map = BeanUtils.bean2map(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        map.put("sex",sex);
//        roomMapper.updateByUserId(user.getUserId());
//        if(StringUtils.isNotNull(roomNum)){
//            SysRoom room = roomMapper.queryByNum(roomNum);
//            room.setUserId(user.getUserId());
//            roomMapper.update(room);
//            map.put("deviceCode", room.getDeviceCode());
//        }
        List<SysRoom> roomList = roomMapper.queryByUserId(user.getUserId());
        map.put("roomList", roomList);
        return map;
    }

    @Override
    public List<SysReport> queryReport(Long userId) {
        return reportMapper.queryByUserId(userId);
    }

    @Override
    public List<Surver> queryAllSurver() {
        return surverMapper.queryAll();
    }

    @Override
    public void addAnswer(List<SurverAnswer> answerList) {
        for (SurverAnswer answer:answerList) {
            answerMapper.deleteAnswer(answer.getUserId(),answer.getProblemId());
        }
        answerMapper.insertBatch(answerList);
    }

    @Override
    public List<Map<String,Object>> queryAnswer(Long userId, Long surverId) {
        List<Map<String,Object>> list = new ArrayList<>();
        List<SurverAnswer> answerList = answerMapper.queryByUserIdAndSurverId(userId,surverId);
        List<SurverProblem> problemList = problemMapper.queryProblemBySurverId(surverId);
        for (SurverProblem problem:problemList) {
            Map<String,Object> map = new HashMap<>();
            map.put("problemId",problem.getProblemId());
            map.put("problemOrderNum",problem.getOrderNum());
            map.put("problemContent",problem.getContent());
            for (SurverAnswer answer:answerList) {
                if(answer.getProblemId().equals(problem.getProblemId())){
                    map.put("answerId",answer.getAnswerId());
                    switch (problem.getType()) {
                        case 1:
                            SurverOption option = optionMapper.queryById(Long.valueOf(answer.getContent()));
                            map.put("answerContent",option.getContent());
                            break;
                        case 2:
                            String[] optionIds = answer.getContent().split(",");
                            String content = optionMapper.queryContentInById(optionIds);
                            map.put("answerContent",content);
                            break;
                        case 3:
                            map.put("answerContent",answer.getContent());
                            break;
                    }
                }
            }
            list.add(map);
        }
        return list;
    }

    @Override
    public List<Map<String,Object>> queryRadarByUserId(Long userId) {
        List<Integer> deviceTypeList = new ArrayList<>();
        deviceTypeList.add(4);
        deviceTypeList.add(5);
        List<Map<String,Object>> list = deviceMapper.queryMapByUserId(userId,deviceTypeList);
        return list;
    }

    @Override
    public List<Map<String,Object>> queryRadarByUser(Long userId) {
        Date date = new Date();
        SysUser user = userMapper.selectUserById(userId);
        List<Map<String,Object>> deviceList = new ArrayList<>();
        boolean isAdmin = false;
        for (SysRole role:user.getRoles()) {
            if(role.getRoleKey().equals("admin")){
                isAdmin = true;
                break;
            }
        }
        List<Integer> deviceTypeList = new ArrayList<>();
        deviceTypeList.add(4);
        deviceTypeList.add(5);
        if(isAdmin){
            deviceList = deviceMapper.queryAllMap(deviceTypeList);
        }else{
            deviceList = deviceMapper.queryMapByDeptId(user.getDeptId(),deviceTypeList);
        }
        List<Map<String,Object>> list = new ArrayList<>();
        for (Map<String,Object> map:deviceList) {
            String online = radarDataMapper.queryOnlineByDeviceCode(map.get("deviceCode").toString(),"online");
            if(StringUtils.isNull(online)){
                map.put("online","0");
            }else{
                map.put("online",online);
                if(online.equals("0")){
                    SysDeviceOmen sdo = deviceOmenMapper.queryByDeviceCodeAndOmenType(map.get("deviceCode").toString(),"设备离线");
                    if(StringUtils.isNull(sdo)) {
                        SysDeviceOmen deviceOmen = new SysDeviceOmen();
                        deviceOmen.setDeviceCode(map.get("deviceCode").toString());
                        deviceOmen.setOmenType("设备离线");
                        deviceOmen.setStatus(0);
                        deviceOmen.setCreateBy("admin");
                        deviceOmen.setCreateTime(date);
                        deviceOmenMapper.insert(deviceOmen);
                    }
                }
            }
            map.put("someoneExists","0");
            list.add(map);
        }
        return list;
    }

    @Override
    public List<Map<String,Object>> queryPdfData() {
        List<Map<String,Object>> list = roomMapper.queryAllUserId();
        return list;
    }

    @SneakyThrows
    @Override
    public Map<String, String> creatEchartImg(Long userId, String deviceCode, Date date, Map<String, Object> map) {
        Map<String,String> echartImgMap = new HashMap<>();
        echartImgMap.put("heartUrl",EchartsUtil.createLine("心率",50, (List<String>) map.get("heartDataX"), (List<Integer>) map.get("heartDataY")));
        echartImgMap.put("respiratoryUrl",EchartsUtil.createLine("呼吸率",0, (List<String>) map.get("respiratoryDataX"), (List<Integer>) map.get("respiratoryDataY")));
        echartImgMap.put("sleepUrl",EchartsUtil.createLineStep("睡眠状态",(List<String>) map.get("sleepDataX"),(List<String>) map.get("sleepDataY"), (List<Integer>) map.get("sleepData")));
        echartImgMap.put("sportsUrl",EchartsUtil.createLineStep("运动体征", (List<String>) map.get("sportsDataX"), (List<String>) map.get("sportsDataY"), (List<Integer>) map.get("sportsData")));

        if(StringUtils.isNotNull(map.get("sleepScale"))){
            SysRadarData radarData = new SysRadarData();
            radarData.setUserId(userId);
            radarData.setDeviceCode(deviceCode);
            radarData.setDeviceType(4);
            radarData.setDeviceDataKey("sleepScale");
            radarData.setDeviceDataValue(map.get("sleepScale").toString());
            radarData.setCreateBy("admin");
            radarData.setCreateTime(date);
            radarDataMapper.insert(radarData);
        }
        return echartImgMap;
    }

    @SneakyThrows
    @Override
    public void insertSleepScale(Long userId, String deviceCode, Date date, Map<String, Object> map) {
        if(StringUtils.isNotNull(map.get("sleepScale"))){
            SysRadarData radarData = new SysRadarData();
            radarData.setUserId(userId);
            radarData.setDeviceCode(deviceCode);
            radarData.setDeviceType(4);
            radarData.setDeviceDataKey("sleepScale");
            radarData.setDeviceDataValue(map.get("sleepScale").toString());
            radarData.setCreateBy("admin");
            radarData.setCreateTime(date);
            radarDataMapper.insert(radarData);
        }
    }

    @Override
    public AjaxResult addDevice(Long userId, String deviceCode, String deviceName, Integer deviceType, String roomNum, String roomName) {
        SysRoom sysRoom = roomMapper.queryByNum(roomNum);
        SysDevice sysDevice = deviceMapper.checkDeviceCodeUnique(deviceCode);
        if(StringUtils.isNotNull(sysDevice)){
            return AjaxResult.error("设备编号重复");
        }
        if(StringUtils.isNotNull(sysRoom)){
            return AjaxResult.error("房间编号重复");
        }
        Date date = new Date();
        SysDevice device = new SysDevice();
        device.setDeptId(Long.valueOf(400));
        device.setDeviceCode(deviceCode);
        device.setDeviceName(deviceName);
        device.setDeviceType(deviceType);
        device.setDeviceSort(0);
        device.setPrice(0.0);
        device.setStatus("0");
        device.setDelFlag("0");
        device.setCreateBy("admin");
        device.setCreateTime(date);
        deviceMapper.insert(device);
        SysRoom room = new SysRoom();
        room.setUserId(userId);
        room.setDeviceCode(deviceCode);
        room.setRoomNum(roomNum);
        room.setRoomName(roomName);
        room.setCreateBy("admin");
        room.setCreateTime(date);
        roomMapper.insert(room);
        return AjaxResult.success();
    }

    @Override
    public void addOmen(Long userId, List<Map> omenList) throws Exception {
        Date date = new Date();
        if(StringUtils.isNotNull(omenList)) {
            for (Map<String, Object> omen : omenList) {
                String deviceCode = omen.get("deviceCode").toString();
                String omenType = omen.get("omenType").toString();
                SysDeviceOmen sdo = deviceOmenMapper.queryByDeviceCodeAndOmenType(deviceCode,omenType);
                if(StringUtils.isNull(sdo)) {
                    SysDeviceOmen deviceOmen = new SysDeviceOmen();
                    deviceOmen.setDeviceCode(deviceCode);
                    deviceOmen.setOmenType(omenType);
                    deviceOmen.setStatus(0);
                    deviceOmen.setCreateBy("admin");
                    deviceOmen.setCreateTime(date);
                    deviceOmenMapper.insert(deviceOmen);

                    SysUser user = userMapper.selectUserById(userId);
                    SmsUtils.sendSms(user.getUrgentPhone(),user.getUrgentName(),omenType,user.getUserName(),user.getPhonenumber());
                }
            }
        }
//        SysUser user = userMapper.selectUserById(userId);
//        List<Integer> deviceTypeList = new ArrayList<>();
//        deviceTypeList.add(4);
//        deviceTypeList.add(5);
//        List<Map<String,Object>> deviceList = deviceOmenMapper.queryUnhandled(user.getDeptId(),deviceTypeList,"online");
//        List<Map<String,Object>> list = new ArrayList<>();
//        for (Map<String,Object> map:deviceList) {
////            String online = radarDataMapper.queryOnlineByDeviceCode(map.get("deviceCode").toString(),"online");
//            if(StringUtils.isNull(map.get("online"))){
//                map.put("online","0");
//            }
//            list.add(map);
//        }
//        return list;
    }

    @Override
    public void handleOmen(Long userId, Long omenId) {
//        SysDeviceOmen deviceOmen = deviceOmenMapper.queryById(omenId);
//        deviceOmen.setStatus(1);
//        deviceOmenMapper.update(deviceOmen);
//        SysUser user = userMapper.selectUserById(userId);
//        List<Integer> deviceTypeList = new ArrayList<>();
//        deviceTypeList.add(4);
//        deviceTypeList.add(5);
//        List<Map<String,Object>> deviceList = deviceOmenMapper.queryUnhandled(user.getDeptId(),deviceTypeList,"online");
//        List<Map<String,Object>> list = new ArrayList<>();
//        for (Map<String,Object> map:deviceList) {
////            String online = radarDataMapper.queryOnlineByDeviceCode(map.get("deviceCode").toString(),"online");
//            if(StringUtils.isNull(map.get("online"))){
//                map.put("online","0");
//            }
//            list.add(map);
//        }
//        return list;
        SysDeviceOmen deviceOmen = deviceOmenMapper.queryById(omenId);
    }

    @Override
    public SysDeviceOmen queryOmenById(Long omenId) {
        return deviceOmenMapper.queryById(omenId);
    }

    @Override
    public List<SysRoom> queryRoomByUser(Long userId) {
        return roomMapper.queryByUserId(userId);
    }

    @Override
    public Map<String, Object> censusData() {
        Map<String,Object> map = new HashMap<>();
        map.put("userTotalData",userMapper.censusUserTotal());
        map.put("familyTotalData",roomMapper.censusFamilyTotal());
        map.put("deviceTotalData",deviceMapper.censusDeviceTotal());
        map.put("omenData",deviceOmenMapper.censusOmen());
        map.put("sexData",userMapper.censusSex());
        map.put("ageData",userMapper.censusAge());
        map.put("heartRateData",radarDataMapper.censusHeartRate());
        map.put("breathData",radarDataMapper.censusBreath());
        map.put("userData",userMapper.censusUser());
        map.put("deviceData",deviceMapper.censusDevice());
        map.put("durationTotalData",radarDataMapper.censusDurationTotal());
        map.put("durationData",radarDataMapper.censusDuration());
        map.put("sleepScaleData",radarDataMapper.censusSleepScale());
        return map;
    }

    @Override
    public SysUser queryUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public void delDevice(Long userId, String deviceCode) {
        SysDevice device = deviceMapper.checkDeviceCodeUnique(deviceCode);
        deviceMapper.deleteById(device.getDeviceId());
        List<SysRoom> roomList = roomMapper.queryByUserId(userId);
        for (SysRoom room:roomList) {
            if(room.getDeviceCode().equals(deviceCode)){
                roomMapper.deleteById(room.getRoomId());
            }
        }
    }

    @Override
    public List<Map<String, Object>> queryCensusData(Long userId, String deviceCode, String dataKey, Integer dateType, String startTime, String endTime) {
        List<Map<String, Object>> list = new ArrayList<>();
        switch (dateType) {
            case 1:
                list = radarDataMapper.queryCensusYearData(userId,deviceCode,dataKey,startTime);
                break;
            case 2:
                list = radarDataMapper.queryCensusMonthData(userId,deviceCode,dataKey,startTime);
                break;
            case 3:
                list = radarDataMapper.queryCensusWeekData(userId,deviceCode,dataKey,startTime,endTime);
                break;
            case 4:
                endTime = startTime + " 24:00:00";
                startTime = startTime + " 00:00:00";
                list = radarDataMapper.queryCensusDayData(userId,deviceCode,dataKey,startTime,endTime);
                break;
        }
        return list;
    }

    @Override
    public List<SysSong> querySong(String keywords) {
        return songMapper.querySong(keywords);
    }

    @Override
    public Map<String, Object> queryFootwave() {
        Map<String,Object> map = new HashMap<>();
        String date = DateUtils.getDate();
        String startTime = date + " 00:00:00";
        String endTime = date + " 24:00:00";
        List<SysMessage> sysMessageList = messageMapper.queryAllGroupByTime(null,startTime,endTime);
        Map<String,Object> waveData = new HashMap<>();
        List<Long> dataX = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            List dataList = new ArrayList();
            for (SysMessage message:sysMessageList) {
                if(i == 0) {
                    dataX.add(message.getId());
                }
                String[] data = message.getMessage().split(",");
                if (Integer.parseInt(data[i]) <= 33) {
                    dataList.add(0);
                } else {
                    dataList.add(data[i]);
                }
            }
            waveData.put("foot" + (i + 1) + "wave",dataList);
        }
        waveData.put("dataX",dataX);
        List<String> waveNum = new ArrayList<>();
        for (SysMessage message:sysMessageList) {
            String[] data = message.getMessage().split(",");
            List<StreamBean> list = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                StreamBean bean = new StreamBean();
                bean.setKey((i + 1) + "");
                if (Integer.parseInt(data[i]) <= 33) {
                    bean.setValue("0");
                } else {
                    bean.setValue(data[i]);
                }
                list.add(bean);
            }
            List<String> list1 = new ArrayList<>();
            list.stream().sorted(Comparator.comparing(StreamBean::getValue).reversed())
                    .forEach(x -> {
                        list1.add(x.getKey());
                    });
            String num = "";
            for (int i = 0; i < list1.size(); i++) {
                num += list1.get(i);
            }
            waveNum.add(num);
        }
        if(CollectionUtils.isEmpty(waveNum)){
            return new HashMap<>();
        }
        Map<String,Long> sort = waveNum.stream().collect(Collectors.groupingBy(k->k, Collectors.counting()));
        map.put("waveData",waveData);
        map.put("waveCensus",sort);
        return map;
    }

    @Override
    public void saveDressData(Long userId, String dataKey, String dataValue, Date now) {
        SysDeviceData deviceData = new SysDeviceData();
        deviceData.setUserId(userId);
        deviceData.setDeviceCode("dress");
        deviceData.setDeviceType(6);
        deviceData.setDeviceDataKey(dataKey);
        deviceData.setDeviceDataValue(dataValue);
        deviceData.setCreateBy("admin");
        deviceData.setCreateTime(now);
        deviceDataMapper.insert(deviceData);
    }

    @Override
    public List<Map<String, Object>> queryDressDataYear(Long userId, String dataKey) {
        String year = DateUtils.dateTimeNow(DateUtils.YYYY);
        return deviceDataMapper.queryDataByYear(userId,dataKey,year);
    }

    @Override
    public List<Map<String, Object>> queryDressDataMonth(Long userId, String dataKey) {
        String month = DateUtils.dateTimeNow(DateUtils.YYYY_MM);
        return deviceDataMapper.queryDataByMonth(userId,dataKey,month);
    }

    @Override
    public List<Map<String, Object>> queryDressDataDay(Long userId, String dataKey) {
        String day = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
        return deviceDataMapper.queryDataByDay(userId,dataKey,day);
    }
}
